<template>
  <!-- 企微导购码管理 -->
  <!-- 企微导购-欢迎语设置 -->
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <div class="title">欢迎语设置</div>
      <div class="warning">
        <img src="https://img.bzhz.jnbygroup.com/dincanwarn.png" alt="" style="">
        <div>
          <div>{{Warningtext1}}</div>
        </div>
      </div>
      <!-- <div class="base">基础设置</div> -->
      <div class="base2">
        <span>设置方式：</span>
        <a-radio-group v-model="radioSetvalue" @change="onChange" v-for="item in setRadio" :key="item.value">
          <a-radio  :value="item.value">
            {{item.name}}
          </a-radio>
        </a-radio-group>
      </div>
      <div>
        <div style="width: 1000px;">
        <a-form-model ref="form" :model="model" :rules="validatorRules">
          <a-form-model-item
            v-if="radioSetvalue == 1"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="storeGroupCode"
            label="门店包">
            <a-select
              v-model="model.storeGroupCode"
              :default-active-first-option="false"
              :filter-option="false"
              :not-found-content="null"
              :options="mdbaoList"
              :show-arrow="false"
              placeholder="输入门店包ID或者名称"
              show-search
              style="width: 250px"
              @search="mdbaoSearch"
              @change="mdbaoChange"
              @focus="mdbaoFocus"
            >
            </a-select>
          </a-form-model-item>
          
          <div v-if="radioSetvalue == 2" style="margin:0 0px 20px 90px;">
            <div style="display:flex;margin-bottom:20px;">
              <a-upload accept=".xls,.xlsx" name="file" :beforeUpload="beforeUpload" :isMultiple="false" @change="handleChange" >
                <a-button type="primary">批量导入</a-button>
                <a-button type="primary" @click="download" style="margin-left:16px;">模板下载</a-button>
              </a-upload>
            </div>
            <div>每次导入以最后一次导入的数据为准</div>
            <div style="margin:20px 0 20px;">
              <a-input placeholder="请输入关键字" style="width:200px;margin-right:10px;" v-model="tablequeryParam" allowClear  />
              <a-button type="primary" @click="tablesearch">搜索</a-button>
            </div>
            <div>
              <a-table 
                ref="table"
                :columns="columns" 
                :data-source="data" 
                :pagination="downloadipag" 
                @change="handleTableChange"
              >
                <span slot="action" slot-scope="text, record">
                  <a @click="handdele(record)">删除</a>
                </span>
              </a-table>
            </div>
          </div>

          <a-form-model-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            prop="welcomeId"
            label="请选择对应规则">
            <a-select 
              show-search
              v-model="model.welcomeId" 
              :show-arrow="false"
              :filter-option="filterOption"
              placeholder="请选择" 
              @change="qwruleChange" 
              @blur="handleExpressBlur"
              style="width:250px;margin-right: 20px;" 
              allowClear
              >
              <a-select-option :value="item.id" v-for="item in qwruleList" :key="item.id"> {{ item.name }} </a-select-option>
            </a-select>
            <a 
              href="#" 
              @click.prevent="ruledetail" 
              class="detailbox" 
              :disabled="model.welcomeId == '' || model.welcomeId == undefined
              ">查看规则细节
            </a>
          </a-form-model-item>
        </a-form-model>
        <div class="detailbox1" v-show="detailshow">
          <div class="item"  v-if="qwruledetail.content.length !== 0">
            <div>文字消息:</div>
            <!-- <div class="content" v-for="content,index in qwruledetail.content" :key="index">{{content}}</div> -->
            <div class="card-info" v-for="(item, index) in cardInfo" :key="index">
              <p v-html="formatCardInfo(item)"></p>
            </div>
          </div>

          <div  class="item" v-if="qwruledetail.imageUrl.length !== 0">
            <div>图片消息:</div>
            <img :src="imageUrl" alt="" class="content" v-for="imageUrl,index in qwruledetail.imageUrl" :key="index">
          </div>

          <div v-for="miniProgramDto,index in qwruledetail.miniProgramDto" :key="index">
            <div class="content">小程序卡片消息:</div>
            <div class="content" v-if="miniProgramDto.text !==''&& miniProgramDto.text !== undefined">
              <div >{{miniProgramDto.text}}</div>
            </div>

            <div class="content" v-if="miniProgramDto.appId !=='' && miniProgramDto.appId !== undefined">
              <div>APPID:{{miniProgramDto.appId}}</div>
            </div>
            <div class="content" v-if="miniProgramDto.url !=='' && miniProgramDto.url !== undefined">
              <div>路径:{{miniProgramDto.url}}</div>
            </div>
            <div class="content" v-if="miniProgramDto.title !=='' && miniProgramDto.title !== undefined">
              <div>标题:{{miniProgramDto.title}}</div>
            </div>

            <div v-if="miniProgramDto.image !=='' && miniProgramDto.image !== undefined">
              <div></div>
              <img :src="miniProgramDto.image" alt="" class="content" >
            </div>
          </div>
        </div>
        </div>
      </div>
      
    </div>
    <div style="text-align:center;">
      <a-button type="primary" @click="save">完成</a-button>
    </div>
    <a-modal v-model="downloadVisible" title="" @ok="downloadhandleOk('人员导入失败数据')" cancelText="取消" okText="下载数据" width="450px">
      <div class="commendContent" v-html="downloadContent" >
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { 
  AllCpWelcome, 
  getWelcomeVoById, 
  getAllStorePkg, 
  setStorePkgWelcome, 
  ImportMember,
  exportMember,
  pageImportMemberVo,
  delImportMember,
  setImportMemberWelcome
} from '@/api/marketingCenter/code'

export default {
  name:'xx',
  data() {
    return {
      Warningtext1:'支持根据门店包批量设置对应门店下所有导购的导购码',
      detailshow: false, // 查看细节显示隐藏
      model: {
        welcomeId:'',
      },
      qwruleList:[],
      mdbaoList:[],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      qwruledetail: {
        miniProgramDto:[],
        content:[],
        imageUrl:[],
      },
      // 校验
      validatorRules: {
        welcomeId: [{ required: true, message: '请选择', trigger: 'blur' }],
        storeGroupCode: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      // 设置方式
      radioSetvalue: 1,
      setRadio:[
        { 
          value:1,
          name:'门店包',
        },
        { 
          value:2,
          name:'人员导入',
        },
      ],
      fileList:[],
      columns: [
        {
          title: '手机号',
          dataIndex: 'mobile',
          key: 'mobile',
        },
        {
          title: '员工名称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
        },
      ],
      data:[],
      downloadipag: {
        current: 1,
        pageSize: 3,
        pageSizeOptions: ['1','2','10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true,
      },
      downloadVisible: false,
      downloadContent: '',
      importCode:"",
      tablequeryParam:"",
      cardInfo: [],
    }
  },
  created() {
    this.getAllCpWelcome()
    this.storeBag()
  },
  computed: {
    formattedCardInfo() {
      const lines = this.content.join("\n")
      let result = ""
      const parser = new DOMParser()
      const doc = parser.parseFromString(lines, "text/html")
      const nodes = doc.body.childNodes
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        if (node.nodeName === "#text") {
          result += node.textContent
        } else if (node.nodeName === "A") {
          result += `<a href="#">${node.textContent}</a>`
        }
      }
      return result
    }
  },
  methods:{
    formatCardInfo(item) {
      let result = ""
      const parser = new DOMParser()
      const doc = parser.parseFromString(item, "text/html")
      const nodes = doc.body.childNodes
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        if (node.nodeName === "#text") {
          result += node.textContent.replace(/\n/g, '<br>')
        } else if (node.nodeName === "A") {
          result += `<a href="#">${node.textContent}</a>`
        }
      }
      return result
    },
    qwruleChange(e) {
      this.model.welcomeId = e
      // 点击切换隐藏查看细节
      this.detailshow = false
    },
    storeBag() {
      getAllStorePkg().then(res =>{
        if(res.code == 200) {
          res.data.forEach((item) => {
            this.mdbaoList.push({
              value: item.storeGroupCode,
              label: item.storePackageId + '\xa0' + item.storePackageName,
            });
          });
        }
      })
    },
    ruledetail() {
      getWelcomeVoById({id:this.model.welcomeId}).then(res =>{
        if(res.code == 200) {
          this.getqwruledetail(res)
          this.detailshow = true
        }
      })
    },
    getqwruledetail(res) {
      this.qwruledetail = {
        content:[],
        imageUrl:[],
        miniProgramDto:[],
      }
      res.data.itemList.forEach(el => {
        if (el.type == 1) {
          this.qwruledetail.content.push(el.content)
          this.cardInfo = this.qwruledetail.content
        } else if (el.type == 2) {
          this.qwruledetail.imageUrl.push(el.imageUrl)
        } else if (el.type == 3) {
          this.qwruledetail.miniProgramDto.push(el.miniProgramDto)
        } 
      });
    },
    getAllCpWelcome() {
      AllCpWelcome().then(res =>{
        if(res.code == 200) {
          this.qwruleList = res.data
        }
      })
    },
    handleExpressBlur(e) {
      this.model.welcomeId = e
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    async mdbaoSearch(value) {
      this.mdbaoList=[];
      const res =  await  getAllStorePkg({'param':value})
      if(res.code == 200) {
        res.data.forEach((item) => {
          this.mdbaoList.push({
            value: item.storeGroupCode,
            label: item.storePackageId + '\xa0' + item.storePackageName,
          });
        });
      }
    },
    mdbaoChange(value) {
      this.model.storeGroupCode = value
    },
    mdbaoFocus() {
      this.mdbaoList=[];
      this.storeBag()
    },
    save() {
      if (this.radioSetvalue == 1) {
        this.getsetStorePkgWelcome()
      } else if (this.radioSetvalue == 2){
        this.getImportMemberWelcome()
      }
    },
    getsetStorePkgWelcome() {
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.model);
          setStorePkgWelcome(this.model).then(res => {
            if (res.code == 200) {
              this.$message.success('操作完成')
              this.$router.push('/marketingCenter/code/shoppecode')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    getImportMemberWelcome() {
      let data = {
        welcomeId:this.model.welcomeId,
        importCode:this.importCode,
      }
      setImportMemberWelcome(data).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          this.$router.push('/marketingCenter/code/shoppecode')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    onChange() {
      console.log('修改设置方式');
      this.model.welcomeId = ''
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file]
      return false
    },
    handleChange(info) {
      if (info.fileList.length > 1) {
        info.fileList.splice(0, 1)
      }
      if (this.fileList.length > 1) {
        this.fileList.splice(0, 1)
      }
      // this.$message.success('批量上传完成')
      let formData = new FormData()
      formData.append('file', this.fileList[0])
      ImportMember(formData).then(res => {
        if (res.code === 200) {
          if (res.msg == '导入成功！') {
            this.$message.success('批量上传成功')
            this.importCode = res.data
            this.getpageImportMemberVo()
          } else {
            // 部分导入成功
            this.$message.warning('部分成功查看原因')
            this.downloadVisible = true;
            this.downloadContent = res.msg
            let arr = this.downloadContent.split(",");
            this.importCode = res.data
            this.getpageImportMemberVo()
            return arr.map((item) => {return item === "\n" ? "<br>" : item}).join("")
          }
        } else {
          this.$message.error(res.msg)
        }
      })
      
    },
    download() {
      window.location.href = 'https://jnbyoss.oss-cn-hangzhou.aliyuncs.com/upload/20230410/61e5994c3d3224591052d3272965a7ac.xlsx'
    },
    // 删除
    handdele(record) {
      delImportMember({id:record.id}).then(res => {
        if (res.code == 200) {
          this.getpageImportMemberVo()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    getpageImportMemberVo() {
      console.log(this.importCode,'importCode');
      let param = {
        importCode:this.importCode,
        queryParam:this.tablequeryParam,
        current:this.downloadipag.current,
        size:this.downloadipag.pageSize,
      }
      pageImportMemberVo(param).then(res => {
        if (res.code == 200) {
          this.data = res.data.records
          this.downloadipag.current = res.data.current
          this.downloadipag.total = res.data.total
        }
      })
    },
    tablesearch() {
      console.log('批量导入搜索');
      this.getpageImportMemberVo()
    },
    handleTableChange(pagination, filters, sorter) {
      //TODO 筛选
      console.log(pagination)
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.downloadipag = pagination
      this.downloadipag.pageSize = pagination.pageSize;
      this.downloadipag.current = pagination.current;
      this.getpageImportMemberVo()
    },
    downloadhandleOk(fileName) {
      this.downloadVisible = false;
      exportMember({importCode:this.importCode}).then(data => {
         if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  }
}
</script>

<style scoped  lang="less" >
.title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 20px;
}
.warning {
  background-color: #fffbe6;
  width: 700px;
  padding:20px 20px 20px 80px;
  margin-left: 20px;
  display: flex;
  img {
    width: 20px;
    height: 20px;
    margin-right:10px;
  }
}
.base {
  margin: 20px;
  font-size: 20px;
  font-weight: 600;
}
.base2 {
  margin: 20px; 
}
/deep/.ant-radio-group {
  line-height: 2.5 !important;
}
.detailbox1 {
  width: 461px;
  margin-top: 20px;
  margin-left: 168px;
  border-radius: 5px;
  padding: 20px;
  background-color: #ccc;
  img {
    width: 100px;
    height: 100px;
  }
  .content {
    margin-bottom: 10px;
    word-wrap: break-word;
  }
  .item {
    margin-bottom: 20px;
  }
}
.commendContent {
  white-space: pre-wrap;
  font-size: 16px;
}
</style>